from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from forms import RegisterForm,LoginForm
from django.contrib.auth import logout,authenticate
from django.contrib.auth.models import User

def login_view(request):
    if request.method == 'POST':
        form = LoginForm(data=request.POST)
        if form.is_valid():
            user = User.objects.get(email=form.cleaned_data['email'])
            if user is not None:   
                username = authenticate(username=user.username, password=form.cleaned_data['password'])
                if username is not None:
                    if username.is_active:
                        #return render_to_response('home.html',{ 'form': form })
                       # login(request, username)   
                        return HttpResponseRedirect("/")
                    else:
                        return render_to_response('inactive.html',{ 'form': form }) 
                else:
                    return  render_to_response('accounts/login.html',{ 'form': form })
            else:
                return render_to_response('accounts/login.html',{ 'form': form }) 
        else:
            return  render_to_response('accounts/login.html',{ 'form': form })
    else:
        form = LoginForm()
    return render_to_response('accounts/login.html', { 'form': form})
            
def register_view(request):
    if request.method == 'POST':
        form = RegisterForm(data=request.POST)
        if form.is_valid():
            new_user = form.save(commit=False)
            new_user.save()
            return HttpResponseRedirect("/")
    else:
        form = RegisterForm()
    return render_to_response('accounts/signup.html',
                              { 'form': form })

def logout_view(request):
    logout(request)
    return HttpResponseRedirect("/")
